from django.db.models import Count, Avg, Q
from django.http import JsonResponse
from django.shortcuts import render
from .models import D_Books
from collections import Counter
import json


def visualization_view(request):
    """渲染可视化页面"""
    # 获取所有数据
    data = get_visualization_data()

    # 获取TOP10作者列表用于选择器
    top_authors = D_Books.objects.values('author').annotate(
        count=Count('id')
    ).exclude(author='未知').order_by('-count')[:10]

    context = {
        'chart_data': json.dumps(data),
        'top_authors': [author['author'] for author in top_authors]
    }
    return render(request, 'visualization.html', context)


def get_books_by_author(request):
    #根据作者获取书籍数据
    author = request.GET.get('author', '')

    # 获取该作者的书籍
    books = D_Books.objects.filter(author=author).order_by('-commend_count')[:10]
    # 准备书籍数据
    book_data = [
        {
            'title': book.title,
            'price': book.price,
            'commend_count': book.commend_count,
            'fav_count': book.fav_count,
            'publisher': book.publisher,
            'tags':book.tags,
            'url':book.url
        }
        for book in books
    ]

    return JsonResponse({'books': book_data})


def get_visualization_data():
    #生成所有可视化数据
    queryset = D_Books.objects.all()

    return {
        # 1. TOP10作者饼图 - 排除"未知"
        'author_pie': list(queryset.values('author')
                           .exclude(author='未知')
                           .annotate(count=Count('id'))
                           .order_by('-count')[:10]),

        # 2. TOP10出版社折线图 - 排除"未知"
        'publisher_line': list(queryset.values('publisher')
                               .exclude(publisher='未知')
                               .annotate(count=Count('id'))
                               .order_by('-count')[:10]),
        # 3. 标签云图
        'tag_cloud': get_tag_cloud_data(queryset),
        # 4. 收藏数与推荐数关系图
        'fav_commend': list(queryset.values('fav_count', 'commend_count')),
        # 5. 价格分布柱状图
        'price_bar': get_price_distribution(queryset),
        # 6. 价格与推荐数气泡图
        'price_commend_bubble': list(queryset.values('price', 'commend_count', 'fav_count'))
    }


def get_price_distribution(queryset):
    # 计算价格分布数据
    ranges = [
        {'label': "负值", 'condition': Q(price__lt=0)},
        {'label': "0-10", 'condition': Q(price__gte=0, price__lt=10)},
        {'label': "10-20", 'condition': Q(price__gte=10, price__lt=20)},
        {'label': "20-30", 'condition': Q(price__gte=20, price__lt=30)},
        {'label': "30-50", 'condition': Q(price__gte=30, price__lt=50)},
        {'label': "50-100", 'condition': Q(price__gte=50, price__lt=100)},
        {'label': "100+", 'condition': Q(price__gte=100)}
    ]

    labels = []
    data = []

    for range_def in ranges:
        labels.append(range_def['label'])
        count = queryset.filter(range_def['condition']).count()
        data.append(count)

    return {'labels': labels, 'data': data}


def get_tag_cloud_data(queryset):
    # 生成标签云数据
    from collections import Counter
    import re

    all_tags = []
    # 获取所有非空标签
    tags_queryset = queryset.exclude(tags__isnull=True).exclude(tags__exact='').values_list('tags', flat=True)

    for tag_str in tags_queryset:
        # 使用正则分割分隔符
        tags = [
            tag.strip()
            for tag in re.split(r'[,\s;]+', tag_str)  # 正则匹配逗号、空格、分号
            if tag.strip()  # 过滤空字符串
        ]
        all_tags.extend(tags)

    if not all_tags:
        return []
    # 统计标签频率
    tag_counter = Counter(all_tags)
    return [{'name': tag, 'value': count} for tag, count in tag_counter.most_common(15)]